package io.zhoujie.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zhoujie.modules.admin.dao.AppUserDao;
import io.zhoujie.modules.admin.entity.AppUserEntity;
import io.zhoujie.modules.app.dao.AppSignDao;
import io.zhoujie.modules.app.entity.AppSignEntity;
import io.zhoujie.modules.app.service.AppSignService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhoujie
 * @email 813685764@qq.com
 * @date 2024/3/15 23:04
 */
@Service("AppSignService")
@Slf4j
public class AppSignServiceImpl extends ServiceImpl<AppSignDao, AppSignEntity> implements AppSignService {
    @Autowired
    private AppSignDao appSignDao;
    @Resource
    private AppUserDao appUserDao;
    @Override
    public int insertSignIn(Integer userId) {
//        创建签到实体
        AppSignEntity appSignEntity = new AppSignEntity();
//        设置实体数据
        appSignEntity.setUserId(userId);
        appSignEntity.setSignDate(LocalDate.now().toDate());
        List<AppSignEntity> list = selectByUserId(userId);
//       遍历获取时间
        List<Date> collect = list.stream().map(item -> item.getSignDate()).collect(Collectors.toList());
//        如果昨天签到则记录连续数值 修改积分数量
        if (collect.contains(LocalDate.now().minusDays(1))&&list.size()>0){
            AppSignEntity flag = list.get(list.size() - 1);
            appSignEntity.setConDays(flag.getConDays());
        }else {
//            否则连续天数为0
            appSignEntity.setConDays(new Integer(0));
        }
        AppUserEntity appUserEntity = appUserDao.selectById(userId);
        appUserEntity.setIntegral(appUserEntity.getIntegral()+1);
        appUserDao.updateById(appUserEntity);
        return appSignDao.insert(appSignEntity);
    }

    @Override
    public List<AppSignEntity> selectByUserId(Integer userId) {
        List<AppSignEntity> list = appUserDao.selectUserList(userId);
        return list;
    }

    @Override
    public Integer selectTopToday(Integer userId) {
        Integer top = appSignDao.selectTopToday(userId);
        return top;
    }

    /**
     * 查询签到列表
     * @param appSignEntity
     * @return
     */
    @Override
    public List<AppSignEntity> selectSignList(AppSignEntity appSignEntity) {
        List<AppSignEntity> appSignEntities = appSignDao.selectSignList(appSignEntity);
        return appSignEntities;
    }

    @Override
    public void deleteByUserId(Integer[] id) {
        appSignDao.deleteByUserId(id);
    }

}
